<template>
  <section class="gif-code">
    <div style="text-align: center; padding-bottom: 20px">
      <img
        :src="'/api/code/getGifCode/' + timeStamp"
        style="cursor: pointer"
        @click="timeStamp = new Date().getTime()"
      >
    </div>
    <el-form ref="form_gifCode" :model="form_gifCode" :rules="rules_gifCode">
      <el-form-item prop="code">
        <el-input
          v-model="form_gifCode.code"
          autofocus
          placeholder="请输入验证码"
        />
        <!--解决表单单输入框回车自动提交问题-->
        <el-input
          v-show="false"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="submitForm('form_gifCode')">
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
export default {
  name: 'GifCode',
  data() {
    const validateGifCode = async (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else {
        // 检测 gifCode 是否正确
        try {
          const res = await this.$axios.$get('/api/code/isCode/' + value)
          if (res.status === 200) {
            callback()
          } else {
            // 重置表单
            this.resetGifCode()
            callback(new Error(res.msg))
          }
        } catch (err) {
          callback(new Error(err))
        }
      }
    }

    return {
      timeStamp: new Date().getTime(),
      form_gifCode: {
        code: ''
      },
      rules_gifCode: {
        code: [
          {
            required: true,
            validator: validateGifCode,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 关闭弹窗
          this.$emit('closeGifCode', false)
          // 重置表单
          this.resetGifCode()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetGifCode() {
      this.timeStamp = new Date().getTime()
      // 重置输入框
      this.form_gifCode.code = ''
    }
  }
}
</script>

<style scoped lang="scss">

  @import "~assets/css/public";
  .gif-code {
    /deep/ .el-form {
      .el-form-item {
        .el-form-item__content {
          display: flex;
          justify-content: flex-end;

          button.el-button {
            background: $theme-color;
            color: #fff;
          }
        }
      }
    }
  }
</style>
